package logic

import (
	"context"
	"fmt"
	"weipinghui/models/cache"
	"weipinghui/models/mysql"
	"weipinghui/models/pkg"

	"weipinghui/weipinghuirpc/internal/svc"
	"weipinghui/weipinghuirpc/weipinghuirpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type RegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RegisterLogic) Register(in *weipinghuirpc.RegisterRequest) (*weipinghuirpc.RegisterResponse, error) {
	// todo: add your logic here and delete this line
	get := cache.RedisDB.Get(l.ctx, "captcha"+"register"+in.Mobile)
	if get.Val() != in.CaptchaCode {
		return nil, fmt.Errorf("图形验证码错误，请重新输入")
	}
	smsCode := cache.RedisDB.Get(l.ctx, "sendSms"+"register"+in.Mobile)
	if smsCode.Val() != in.SmsCode {
		return nil, fmt.Errorf("短信验证码错误，请重新输入")
	}

	var finduser mysql.User
	mysql.DB.Debug().Where("mobile = ?", in.Mobile).Find(&finduser)
	if finduser.ID != 0 {
		return nil, fmt.Errorf("当前账户已注册，请前往登录")
	}
	user := mysql.User{
		Mobile:   in.Mobile,
		Password: pkg.Md5(in.Password),
	}
	err := mysql.DB.Debug().Create(&user).Error
	if err != nil {
		return nil, fmt.Errorf("注册失败")
	}
	cache.RedisDB.Del(l.ctx, "captcha"+"login"+in.Mobile)
	cache.RedisDB.Del(l.ctx, "sendSms"+"login"+in.Mobile)
	return &weipinghuirpc.RegisterResponse{
		Id: int64(user.ID),
	}, nil
}
